# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：attr路由
"""
import math

from fastapi import APIRouter, Query, HTTPException
from typing import Union

from curd.attr import attr_add_curd, attr_edit_curd
from models.base import Attribute

from core.Response import base_response
from schemas.attr import AttrOutSchemas, AttrResponseSchemas, AttrPageListResponseSchemas, AttrAddSchemas, \
    AttrEditSchemas
from schemas.base import BaseResponse

attr_router = APIRouter(prefix='/attrs')


@attr_router.post('', summary='增加商品属性', response_model=Union[AttrResponseSchemas, BaseResponse])
async def attr_add(post: AttrAddSchemas):
    try:
        attr = await attr_add_curd(post)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"增加商品属性失败！失败原因为:{e}")
    return base_response(code=200, msg='增加商品属性成功！', data=attr)


@attr_router.delete('/{id}', summary='删除商品属性', response_model=BaseResponse)
async def attr_del(id: int):
    attr = await Attribute.get_or_none(id=id)
    if not attr:
        return base_response(code=422, msg='该商品属性不存在！')
    try:
        await attr.delete()
        return base_response(code=200, msg='删除商品属性成功！')
    except Exception as e:
        return base_response(code=500, msg=f"删除商品属性失败！失败原因为:{e}")


@attr_router.put('', summary='编辑商品属性', response_model=Union[AttrResponseSchemas, BaseResponse])
async def attr_edit(post: AttrEditSchemas):
    try:
        attr = await attr_edit_curd(post)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"编辑商品属性失败！失败原因为:{e}")
    return base_response(code=200, msg='编辑商品属性成功！', data=attr)


@attr_router.get('', summary='商品属性列表', response_model=Union[AttrPageListResponseSchemas])
async def attr_list(page: int = 1, pageSize: int = 5, type: str = 'static'):
    total = await Attribute.filter(_type=type).all().count()
    items = await Attribute.filter(_type=type).all().limit(pageSize).offset((page - 1) * pageSize)
    data = {
        "page": page,
        "pages": math.ceil(total / pageSize),
        "total": total,
        "data": [AttrOutSchemas(**dict(item), type=type) for item in items]
    }
    return base_response(code=200, msg='商品属性列表获取成功！', data=data)


@attr_router.get('/{id}', summary='商品属性详情', response_model=Union[AttrResponseSchemas, BaseResponse])
async def attr_detail(id: int):
    attr = await Attribute.get_or_none(id=id)
    if not attr:
        return base_response(code=422, msg='该商品属性不存在！')
    return base_response(code=200, msg='商品属性详情获取成功！', data=AttrOutSchemas(**dict(attr), type=attr._type))
